//
//  ForgetpwdViewController.m
//  LocomotiveGuards
//
//  Created by admin on 15/11/19.
//  Copyright (c) 2015年 REDOOR. All rights reserved.
//

#import "ForgetpwdViewController.h"
#import "PopLoadMsg.h"
#import "PopMsg.h"
#import "SetnewpwdViewController.h"
#define kAlphaNum @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"


@interface ForgetpwdViewController ()
{
    UITextField *_fieldPhone;
    UITextField *_fieldCode;
    UIButton *_btnGetCode;
    UILabel *_tipLabel;
    UIButton *_btnNext;
    UILabel *_timeLabel;
    NSTimer *_timer;
    NSInteger k;
    BOOL start;
    BOOL end;
    NSMutableString *result;
    NSInteger flagPhone;
    BOOL canclicked;//判断下一步按钮是否可以点击的参数
}


@end

@implementation ForgetpwdViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    canclicked=NO;
    // Do any additional setup after loading the view.
    [self.leftbtn setTitle:@"" forState:UIControlStateNormal];
    [self.leftbtn setImage:[UIImage imageNamed:@"back01"] forState:UIControlStateNormal];
    [self addTitle:@"忘记密码"];
    [self configView];

}


//停止定时器
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_timer invalidate];
    _timer = nil;
}

- (void)configView
{
    //提示：手机号码验证
    UILabel *label_phoneVerify = [[UILabel alloc] initWithFrame:CGRectMake(20*W, SCREEN_HEIGHT/2-120*H, SCREEN_WIDTH-40*W, 30*H)];
    label_phoneVerify.text = @"手机号码验证";
    label_phoneVerify.textAlignment = 1;
    label_phoneVerify.textColor = [UIColor whiteColor];
    label_phoneVerify.font = [UIFont systemFontOfSize:26];
    [self.view addSubview:label_phoneVerify];
    
   
    //手机号输入框
    _fieldPhone = [[UITextField alloc] initWithFrame:CGRectMake(20*W, CGRectGetMaxY(label_phoneVerify.frame)+20*H, SCREEN_WIDTH-40*W, 35*H)];
    _fieldPhone.backgroundColor = [UIColor whiteColor];
    _fieldPhone.borderStyle = UITextBorderStyleRoundedRect;
    _fieldPhone.placeholder = @"输入手机号";
    _fieldPhone.textAlignment = 1;
    _fieldPhone.font = [UIFont systemFontOfSize:17];
    _fieldPhone.keyboardType = UIKeyboardTypeNumberPad;
    _fieldPhone.delegate = self;
    [self.view addSubview:_fieldPhone];
    
    //验证码输入框
    _fieldCode = [[UITextField alloc] initWithFrame:CGRectMake(20*W, CGRectGetMaxY(_fieldPhone.frame)+15*H, (CGRectGetWidth(_fieldPhone.frame)-5)*0.65, 35*H)];
    _fieldCode.backgroundColor = [UIColor whiteColor];
    _fieldCode.borderStyle = UITextBorderStyleRoundedRect;
    _fieldCode.placeholder = @"输入验证码";
    _fieldCode.textAlignment = 1;
    _fieldCode.font = [UIFont systemFontOfSize:17];
    _fieldCode.keyboardType=UIKeyboardTypeNumberPad;
    _fieldCode.delegate = self;
    [self.view addSubview:_fieldCode];
    
    //显示验证码倒计时label
    _timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.15*CGRectGetWidth(_fieldCode.frame), 0.1*CGRectGetHeight(_fieldCode.frame), 0.7*CGRectGetWidth(_fieldCode.frame), 0.8*CGRectGetHeight(_fieldCode.frame))];
    _timeLabel.backgroundColor = [UIColor clearColor];
    _timeLabel.text = @"";
    _timeLabel.textColor = [UIColor grayColor];
    _timeLabel.font = [UIFont systemFontOfSize:13];
    _timeLabel.textAlignment = 1;
    [_fieldCode addSubview:_timeLabel];
    _timeLabel.hidden = YES;
    
    //获取验证码按钮
    _btnGetCode = [UIButton buttonWithType:UIButtonTypeCustom];
    _btnGetCode.frame = CGRectMake(20*W+CGRectGetWidth(_fieldCode.frame)+5, CGRectGetMaxY(_fieldPhone.frame)+15*H, (CGRectGetWidth(_fieldPhone.frame)-5)*0.35, 35*H);
    [_btnGetCode setBackgroundImage:[UIImage imageNamed:@"3pic_getcode"] forState:UIControlStateNormal];
    [_btnGetCode setBackgroundImage:[UIImage imageNamed:@"3pic_getcode_on"] forState:UIControlStateSelected];
    [_btnGetCode setTitle:@"获取验证码" forState:UIControlStateNormal];

    _btnGetCode.titleLabel.font = [UIFont systemFontOfSize:12];
    [_btnGetCode addTarget:self action:@selector(getCode:) forControlEvents:UIControlEventTouchUpInside];
    
    [self enableButton:_btnGetCode];
    [self.view addSubview:_btnGetCode];
    
    //验证码错误提示信息
    _tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(20*W, CGRectGetMaxY(_fieldCode.frame)+15*H, SCREEN_WIDTH-40*W, 15*H)];
    _tipLabel.text = @"※验证码错误请重新输入";
    _tipLabel.textColor = [UIColor cyanColor];
    _tipLabel.textAlignment = 1;
    _tipLabel.font = [UIFont systemFontOfSize:15];
    [self.view addSubview:_tipLabel];
    _tipLabel.hidden = YES;
    
    //下一步按钮
    _btnNext = [UIButton buttonWithType:UIButtonTypeCustom];
    _btnNext.frame = CGRectMake(SCREEN_WIDTH-100*W, SCREEN_HEIGHT-90*H, 60*W, 30*H);
    [_btnNext setTitle:@"下一步" forState:UIControlStateNormal];
    
    _btnNext.titleLabel.font = [UIFont systemFontOfSize:20];
    [_btnNext addTarget:self action:@selector(btnNextClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self disableButton:_btnNext];
    [self.view addSubview:_btnNext];
   
    
}

#pragma mark - 网络请求
//获取验证码请求
- (void)verifyCodeRequest
{
    canclicked=NO;
    start=YES;
    end=YES;
    PopLoadMsg *loadmsg=[PopLoadMsg new];
    
    NSDictionary *paramdic=@{@"loginId":_fieldPhone.text,@"type":@"1"};
    NSString *url = [urlstring stringByAppendingString:@"getVerifyCode.do"];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        sleep(startloadtime);
        dispatch_async(dispatch_get_main_queue(), ^{
            if(start==YES){
                [loadmsg loadImages];
            }
        });
    });
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        sleep(startloadtime+endloadtime);
        dispatch_async(dispatch_get_main_queue(), ^{
            end=NO;
            if(start==NO){
                [loadmsg.imageview removeFromSuperview];
            }
        });
    });
    
    [K_AppDelegate GenerateHTTPRequestWithUrl:url withParam:paramdic success:^(AFHTTPRequestOperation *op,id responseObject){
        start=NO;
        if(end==NO){
            [loadmsg.imageview removeFromSuperview];
        }
        NSDictionary *dic = [NSDictionary new];
        if ([responseObject isKindOfClass:[NSData class]]) {
            NSLog(@"responseObject = %@", responseObject);
            dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        }
        else if ([responseObject isKindOfClass:[NSDictionary class]])
        {
            dic = (NSDictionary *)responseObject;
        }
        //        RegModel *model = [RegModel new];
        //        [model setValuesForKeysWithDictionary:dic];
        NSInteger flag = [[dic objectForKey:@"flag"] integerValue];
        NSString *msg = [dic objectForKey:@"msg"];
        result = [dic objectForKey:@"result"];
        if (msg) {
            NSString *message=[msg stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            [PopMsg showMessage:message Lasttime:1.0f];
        }
        if(flag == 0){
            //获取验证码成功
            canclicked=YES;
            NSLog(@"result = %@", result);
            _fieldCode.placeholder = @"";
            _timeLabel.hidden =YES;
            _tipLabel.hidden = YES;
            _fieldCode.text = @"";
            k = 60;
            [self disableButton:_btnGetCode];
           
            NSString *text=[NSString stringWithFormat:@"倒计时%i秒",k--];
            [_btnGetCode setTitle:text forState:UIControlStateDisabled];
            //_timeLabel.text = [NSString stringWithFormat:@"验证码%i秒后失效",k];
            
            _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timer:) userInfo:nil repeats:YES];
        }
        
    }failure:^(AFHTTPRequestOperation *op,NSError *error){
        start=NO;
        if(end==NO){
            [loadmsg.imageview removeFromSuperview];
        }
        NSLog(@"error = %@", error);
        [PopMsg showMessage:@"网络异常，请重试" Lasttime:1.0f];
    }];
}

//验证手机号请求
- (void)verifyPhoneRequest
{
    start=YES;
    end=YES;
    PopLoadMsg *loadmsg=[PopLoadMsg new];
    
    NSDictionary *paramdic=@{@"loginId":_fieldPhone.text,
                             @"verifyCode":_fieldCode.text,
                             @"type":@"1"};
    NSString *url = [urlstring stringByAppendingString:@"verifyPhoneNum.do"];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        sleep(startloadtime);
        dispatch_async(dispatch_get_main_queue(), ^{
            if(start==YES){
                [loadmsg loadImages];
            }
        });
    });
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        sleep(startloadtime+endloadtime);
        dispatch_async(dispatch_get_main_queue(), ^{
            end=NO;
            if(start==NO){
                [loadmsg.imageview removeFromSuperview];
            }
        });
    });
    
    [K_AppDelegate GenerateHTTPRequestWithUrl:url withParam:paramdic success:^(AFHTTPRequestOperation *op,id responseObject){
        start=NO;
        if(end==NO){
            [loadmsg.imageview removeFromSuperview];
        }
        NSDictionary *dic = [NSDictionary new];
        if ([responseObject isKindOfClass:[NSData class]]) {
            NSLog(@"responseObject = %@", responseObject);
            dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        }
        else if ([responseObject isKindOfClass:[NSDictionary class]])
        {
            dic = responseObject;
        }
        
        flagPhone = [[dic objectForKey:@"flag"] integerValue];
        NSString *msg = [dic objectForKey:@"msg"];
        if (msg) {
            NSString *message=[msg stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            //[PopMsg showMessage:message Lasttime:1.0f];
        }
        [self getnext];
        
        NSLog(@"flagPhone = %i", flagPhone);
        
    }failure:^(AFHTTPRequestOperation *op,NSError *error){
        start=NO;
        if(end==NO){
            [loadmsg.imageview removeFromSuperview];
        }
        NSLog(@"error = %@", error);
        [PopMsg showMessage:@"网络出错" Lasttime:1.0f];
    }];
}


#pragma mark - 点击事件
//获取验证码
- (void)getCode:(UIButton *)btn
{
    if(_fieldPhone==nil || _fieldPhone.text.length==0){
        _tipLabel.text = @"※手机号码不能为空";
         _tipLabel.hidden = NO;
        
    }
    else if(_fieldPhone.text.length!=11){
        _tipLabel.text = @"※手机号码位数不对";
         _tipLabel.hidden = NO;
    }
    else{
            [self verifyCodeRequest];
        
    
    }

}

-(void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBar.hidden=YES;
    canclicked=NO;
}

-(void)timer:(NSTimer*)timer
{
    [self disableButton:_btnGetCode];
    //_timeLabel.text = [NSString stringWithFormat:@"验证码%i秒后失效",k-1];
    NSString *text=[NSString stringWithFormat:@"倒计时%i秒",k--];
    [_btnGetCode setTitle:text forState:UIControlStateDisabled];
    
    if (k==-1) {
        canclicked=NO;
        [self enableButton:_btnGetCode];
        [self disableButton:_btnNext];
        [_timer invalidate];
        k=60;
        _fieldCode.placeholder = @"输入验证码";
        _timeLabel.hidden = YES;
    }
    
}

//下一步
- (void)btnNextClicked:(id)sender
{
    [self verifyPhoneRequest];
    
}

-(void)getnext{
    if (flagPhone == -1) {
        _tipLabel.text = @"※验证码错误请重新输入";
        
        _tipLabel.hidden = NO;
    }
    else if(flagPhone==0){
        SetnewpwdViewController *new=[SetnewpwdViewController new];
        new.phone=_fieldPhone.text;
        [self enableButton:_btnGetCode];
        [self disableButton:_btnNext];
        [_timer invalidate];
        k=60;
        _fieldCode.placeholder = @"输入验证码";
        _timeLabel.hidden = YES;
        new.verificationCode=result;
        [self.navigationController pushViewController:new animated:YES];
    }
    else if(flagPhone==1){
        _tipLabel.text = @"※手机号码未激活";
        
        _tipLabel.hidden = NO;
    }
    else{
       
    }
}

//收起键盘
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [_fieldPhone resignFirstResponder];
    [_fieldCode resignFirstResponder];
}

#pragma mark - UITextFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == _fieldPhone) {
        if (textField.text.length >= 11)
        {
            if ([string isEqual:@""])
            {
                return YES;
            }
            return NO;
        }

    }
    return YES;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if (textField == _fieldCode) {
        _timeLabel.hidden = YES;
    }
    return YES;
}

//- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
//{
//    //当验证码输入框没有输入任何信息，验证码输入框注销响应时，继续显示倒计时
//    if ([_fieldCode.text isEqualToString:@""]) {
//        _timeLabel.hidden = NO;
//    }
//    return YES;
//}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [_fieldPhone resignFirstResponder];
    [_fieldCode resignFirstResponder];
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if (_fieldPhone.text.length == 11 && _fieldCode.text.length == result.length && canclicked==YES) {
        [self enableButton:_btnNext];
    }
    else{
        [self disableButton:_btnNext];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
